/**
*
* 1.平衡點問題 平衡點:比如int[] numbers = {1,3,5,7,8,25,4,20};
* 25前面的總和爲24,25後面的總和也是24,25這個點就是平衡點;假如一個數組中的元素,其前面的部分等於後面的部分,那麼這個點的位序就是平衡點
* 要求:返回任何一個平衡點
*
* @author fangtengfei
* @date 2010-5-15
*/
public class BalancePoint {
public static void main(String[] args) {
// 有平衡點,且平衡點是個數據
int[] hasBalancePointValueNumbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
// 有平衡點,且平衡點是索引
int[] hasBalancePointIndexNumbers = { 1, 3, 5, 7, 8, 4, 20 };
// 無平衡點
int[] noBalancePointNumbers = { 1, 3, 5, 7, 8, 4, 20, 12, 13 };
}
private static int queryBalancePoint(int[] noBalancePointNumbers) {
int frontIndex = 0, backIndex = noBalancePointNumbers.length - 1;
int temp = 0;
// 判斷前後索引不相等,那臨時數減去前面的大於零則++,小於0則--
while (frontIndex != backIndex) {
if (temp - noBalancePointNumbers[frontIndex] >= 0) {
temp -= noBalancePointNumbers[frontIndex];
frontIndex++;
} else {
temp += noBalancePointNumbers[backIndex];
backIndex--;
}
}
// 當索引一樣時,臨時數等於0則返回當前數,<>0則返回當前索引。
if (backIndex - frontIndex == 0) {
if (temp == 0) {
return noBalancePointNumbers[frontIndex];
}
if (temp - noBalancePointNumbers[frontIndex] == 0) {
return frontIndex;
}
}
return -1;
}
}